/**
 * Copyright 2007 Christian Mueller
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
 * use this file except in compliance with the License. You may obtain a copy of 
 * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by 
 * applicable law or agreed to in writing, software distributed under the License 
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
 * either express or implied. See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * Description:
 * This file provide the logging mechanism for this application
 * 
 */
#include "myglobal.h"
#include "logging.h"
#include <addin.h>

/*
 * This variable defines the current loglevel
 */
loglevel current_level = LOG_INFO;

/*
 * With this function, the current loglevel could be set
 */
void logging_set_loglevel(loglevel newLevel) {
	current_level = newLevel;
}

/*
 * With this function, the current loglevel could be retrieved
 */
loglevel logging_get_loglevel() {
	return current_level;
}
	
const char loglevelname[][256] =
	{ 
		"Fatal",
		"Error",
		"Warning",
		"Info",
		"Debug0",
		"Debug1",
		"Debug2",
		"Debug3",
		"Debug4",
	   };

/*
 * Function to get the current loglevel as string
 */
const char* logging_get_logname(loglevel level) {
	return loglevelname[level];
}

/*
 * Function to get the current loglevel as string
 */
const char* logging_get_current_logname() {
	return logging_get_current_logname(current_level);
}

char applicationName[1024] = "Unknown";

/* Function to set the application name */
void logging_set_applicationName(const char* newName)
{
	if (strlen(newName)<1024)
		strcpy(applicationName,newName);
}

/* Private function that prints a logtext */
void logging_write_log_direct(const char* message) {
	/* TODO Use not printf in future */
	// printf("%s\n",message);
	AddInLogMessageText((char*)message, NOERROR);
}

/* Private function that prints a logtext with level */
void logging_write_log(loglevel level, const char* message) {
	/* Check if logging is needed at all */
	if (level<=current_level) {
		char newmessage[1024];
		
		if (strlen(message)>768) {
			logging_write_log_direct("FATAL: LOGMESSAGE TO LONG....\n");
			return;
		} 
		
		/* Build full string */
		strcpy(newmessage,applicationName);
		strcat(newmessage," - ");
		strcat(newmessage,logging_get_logname(level));
		strcat(newmessage,": ");
		strcat(newmessage,message);
		
		/* Write Message with loglevel */
		logging_write_log_direct(newmessage);	
	}
}



